#include "autoupdate.h"

#include <QApplication>
#include <QDateTime>
#include <QFile>
#include <QMutex>
#include <QDir>
#include <QScreen>
void outPutMsg(QtMsgType msgType, const QMessageLogContext &context, const QString &strText)
{
    static QMutex mutex;
    mutex.lock();

    QString strMsg("");
    // 设置输出信息格式


    switch (msgType) {
    case QtDebugMsg: {
        strMsg = QString("Debug");
        break;
    }
    case QtInfoMsg: {
        strMsg = QString("Info");
        break;
    }
    case QtWarningMsg: {
        strMsg = QString("Warning");
        break;
    }
    case QtCriticalMsg: {
        strMsg = QString("Critical");
        break;
    }
    case QtFatalMsg: {
        strMsg = QString("Fatal");
        break;
    }
    }

    QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString fileName =context.file;
    QStringList listStr = fileName.split("/"); // 以空格为分隔符进行分割
    fileName=listStr.at(listStr.size()-1);
    QString strMessage = QString("[%1][%2][%3]-%4:%5\r\n").arg(strDateTime).arg(fileName).arg(context.line).arg(strMsg).arg(strText);

    QString strPlaceDir = QCoreApplication::applicationDirPath()+"/log";//当前程序运行路径
    QDir directory(strPlaceDir);//如果路径不存在，则创建
    if (!directory.exists())
        directory.mkpath(strPlaceDir);
    QString logFileName =strPlaceDir+"/"+QString(QDate::currentDate().toString("yyyy-MM-dd") + ".txt");
    QFile file(logFileName);
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(&file);
    text_stream<<strMessage;
    file.close();

    fprintf(stderr, strMessage.toLocal8Bit().data());
    fflush(stderr);
    // 解锁
    mutex.unlock();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    qInstallMessageHandler(outPutMsg);
    //qDebug()<<argc;
    QStringList g_args;
    for(int i=0;i<argc;i++)
        g_args<<argv[i];

    if(argc!=4)
    {

        QString strInfo ="无有效输入参数！\n"+ g_args.join(",");
        qDebug()<<strInfo;
        QMessageBox::information(NULL, "提示",strInfo);

        return 0;
    }

    AutoUpdate w;
    w.show();
    w.initAutoUpdate(g_args);
    return a.exec();
}
